import os,time
import socket
import RPi.GPIO as GPIO

host = '0.0.0.0'
port = 2014
thr_pin_id = 3
ele_pin_id = 7
frequence = 100

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host,port))
    sock.listen(0)
    print 'begin listen..'

    request, addr = sock.accept()
    #print addr
    print addr[0]+'connected, gpio start!'
    g = gpio()
    while True:
        data = request.recv(20)
        print 'recieved:'+data

        if data=='bye':
            print 'bye bye'
            g.stop()
            request.close()
            sock.close()
            break
        else:
            if ':' not in data:
                continue

            name = data.split(':')[0]
            value = data.split(':')[1]

            if not value.isdigit():
                continue
            
            value = int(value)
            if value>=0 and value<=100:
                pin = ele_pin_id if name=='ele' else thr_pin_id
                g.change(pin,value)
            print data
        time.sleep(5)

class gpio:
    ele_pin = None
    thr_pin = None

    def __init__(self):
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(ele_pin_id,GPIO.OUT)
        GPIO.setup(thr_pin_id,GPIO.OUT)

        self.ele_pin = GPIO.PWM(ele_pin_id,frequence)
        self.ele_pin.start(0)

        self.thr_pin = GPIO.PWM(thr_pin_id,frequence)
        self.thr_pin.start(0)

    def change(self,id,dc):
        if id == ele_pin_id:
            self.ele_pin.ChangeDutyCycle(dc)
            print 'ele:'+str(dc)

        if id == thr_pin_id:
            self.thr_pin.ChangeDutyCycle(dc)
            print 'thr:'+str(dc)

    def stop(self):
        self.ele_pin.stop()
        self.thr_pin.stop()
        GPIO.cleanup()
              
    
if __name__ == '__main__':
    main()








